package com.xk.meeting.dao;

import com.xk.meeting.entity.Message;
import com.xk.meeting.entity.User;
import com.xk.meeting.utils.ConnectionUtils;
import com.xk.meeting.utils.UtilHelper;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class MessageDaoImpl implements MessageDao{
    JdbcTemplate template = new JdbcTemplate(ConnectionUtils.getDataSource());
    @Override
    public void addMessage(Message message) {
        String sql = "insert into message values(null,?,?,?,?,?)";
        template.update(sql,message.getUid(),message.getTitle(),message.getContent(), UtilHelper.getTime(),0);
    }

    @Override
    public Message getUnready(int uid) {
        String sql = "select * from message where uid = ? and status = ?";
        try{
            return template.queryForObject(sql,new BeanPropertyRowMapper<Message>(Message.class),uid,0);
        }catch (DataAccessException e){
            return null;
        }
    }

    @Override
    public List<Message> getMessages(User user) {
        String sql = "select * from message where uid = ? order by id desc";
        return template.query(sql,new BeanPropertyRowMapper<Message>(Message.class),user.getId());
    }

    @Override
    public void updateStatus(int id) {
        String sql = "update message set status = 1 where id = ?";
        template.update(sql,id);
    }

    @Override
    public int delMessage(int id) {
        String sql = "delete from message where id = ?";
        return template.update(sql,id);
    }

}
